<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="/resources/layui/css/layui.css"/>
    <link rel="stylesheet" href="/resources/layui/layui-ext/dtree/dtree.css">
    <link rel="stylesheet" href="/resources/layui/layui-ext/dtree/font/dtreefont.css">

</head>
<body>
<div style="padding: 20px 10px 0px" shiro:hasPermission="user:view">
    <fieldset class="layui-elem-field">
        <legend>查询条件</legend>
        <div class="layui-field-box">
            <form class="layui-form" action="" id="searchFrm">
                <div class="layui-form-item layui-input-inline">
                    <label class="layui-form-label">用户名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" placeholder="请输入用户名称" autocomplete="off"
                               class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item layui-input-inline">
                    <label class="layui-form-label">用户地址</label>
                    <div class="layui-input-inline">
                        <input type="text" name="address" placeholder="请输入用户地址" autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-input-inline">
                    <label class="layui-form-label">用户备注</label>
                    <div class="layui-input-inline">
                        <input type="text" name="remark" placeholder="请输入用户备注" autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item" style="text-align: center;">
                    <div class="layui-input-baddressk">
                        <button type="submit" class="layui-btn" lay-submit="" lay-filter="doSearch">查询</button>
                        <button type="button" class="layui-btn layui-btn-primary" id="doReset" lay-filter="doReset">重置
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </fieldset>
</div>
<table id="userTable" lay-filter="userTable"></table>

<!--toolbar开始-->
<div id="tableToolbar" style="display: none;">
    <button type="button" shiro:hasPermission="user:create" class="layui-btn" lay-event="add">添加</button>
    <button type="button" shiro:hasPermission="user:batchdelete" class="layui-btn layui-btn-danger" lay-event="batchDelete">批量删除</button>
</div>
<div id="cellToolbar" style="display: none;">
    <button type="button" shiro:hasPermission="user:update" class="layui-btn layui-btn-sm layui-btn-xs" lay-event="update">修改</button>
    <button type="button" shiro:hasPermission="user:delete" class="layui-btn layui-btn-danger layui-btn-sm layui-btn-xs" lay-event="delete">删除</button>
    <button type="button" shiro:hasPermission="user:resetpwd" class="layui-btn layui-btn-danger layui-btn-sm layui-btn-xs" lay-event="resetUserPwd">重置密码</button>
    <button type="button" shiro:hasPermission="user:selectRole" class="layui-btn layui-btn-sm layui-btn-xs" lay-event="dispatcherUserRole">分配角色</button>
</div>
<!--toolbar结束-->

<!--添加修改弹出层开始-->
<form class="layui-form" id="addForm" lay-filter="addForm" action="" style="display: none;padding: 20px">
    <div class="layui-form-item">
        <label class="layui-form-label">所在部门</label>
        <div class="layui-input-inline">
            <div class="layui-unselect layui-form-select" id="userdeptaccordiontree">
                <div class="layui-select-title">
                    <input type="hidden" name="id" id="id">
                    <input type="hidden" id="deptid" name="deptid" required class="layui-input layui-unselect">
                    <input type="text" name="deptname" id="userdeptaccordiontreename" placeholder="请选择" required
                           readonly="" class="layui-input layui-unselect">
                    <i class="layui-edge"></i>
                </div>
            </div>
            <div class="layui-card" id="test" name="divuser">
                <div class="layui-card-body">
                    <div id="toolbarDiv">
                        <ul id="userdepttree" class="dtree" data-id="0" style="width: 100%;"></ul>
                    </div>
                </div>
            </div>
        </div>
        <label class="layui-form-label">排序码</label>
        <div class="layui-input-inline">
            <input type="text" id="ordernum" name="ordernum" required lay-verify="required|number"
                   autocomplete="off"
                   placeholder="请输入排序码"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">领导部门</label>
        <div class="layui-input-inline">

            <div class="layui-unselect layui-form-select" id="leaderdeptaccordiontree">
                <div class="layui-select-title">
                    <input type="hidden" id="leaderdeptid" name="leaderdeptid" required
                           class="layui-input layui-unselect">
                    <input type="text" name="leaderdeptname" id="leaderdeptname" placeholder="请选择" required
                           readonly="" class="layui-input layui-unselect">
                    <i class="layui-edge"></i>
                </div>
            </div>
            <div class="layui-card" id="test" name="divleader">
                <div class="layui-card-body">
                    <div id="toolbarDiv">
                        <ul id="leaderdepttree" class="dtree" data-id="0" style="width: 100%;"></ul>
                    </div>
                </div>
            </div>
        </div>
        <label class="layui-form-label">领导姓名</label>
        <div class="layui-input-inline">
            <!--<input type="hidden" name="mgr" id="mgr"   >-->
            <select id="deptSelect" name="mgr" lay-verify="required">
                <option value="">请选择领导姓名</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">用户名称</label>
        <div class="layui-input-inline">
            <input type="text" id="name" name="name" required lay-verify="required" autocomplete="off"
                   placeholder="请输入用户名称"
                   class="layui-input">
        </div>
        <label class="layui-form-label">登录名称</label>
        <div class="layui-input-inline">
            <input type="text" id="loginname" name="loginname" required lay-verify="required" autocomplete="off"
                   placeholder="请输入登录名称"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">用户备注</label>
        <div class="layui-input-block">
            <textarea name="remark" id="remark" required lay-verify="required" placeholder="请输入"
                      class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">用户地址</label>
        <div class="layui-input-inline">
            <input type="text" id="address" name="address" required lay-verify="required" autocomplete="off"
                   placeholder="请输入用户地址"
                   class="layui-input">
        </div>
        <label class="layui-form-label">入职时间</label>
        <div class="layui-input-inline">
            <input type="text" id="hiredate" name="hiredate" class="layui-input"
                   placeholder="yyyy-MM-dd">

        </div>
    </div>


    <div class="layui-form-item">
        <label class="layui-form-label">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="sex" value="1" title="男" checked>
            <input type="radio" name="sex" value="0" title="女">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">是否可用</label>
        <div class="layui-input-block">
            <input type="radio" name="available" value="1" title="可用" checked>
            <input type="radio" name="available" value="0" title="不可用">
        </div>
    </div>


    <div class="layui-input-block">
        <div align="center">
            <button type="submit" class="layui-btn" id="release" lay-submit="" lay-filter="release">保存</button>
            <button type="button" class="layui-btn layui-btn-danger" id="cancel">取消</button>

        </div>
    </div>
</form>
<!--添加修改弹出层结束-->

<!--分配角色弹出层开始-->
<div id="dispatcherRoleDiv" STYLE="display: none">
    <table id="roleTable" lay-filter="roleTable"></table>
</div>
<!--分配角色弹出层结束-->
<script src="/resources/layui/layui.js"></script>
<script>
    var tableIns;
    layui.extend({
        dtree: '/resources/layui/layui-ext/dtree/dtree'
    }).use(['table', 'form', 'jquery', 'dtree', 'laydate'], function () {
        var table = layui.table;
        var form = layui.form;
        var $ = layui.jquery;
        var laydate = layui.laydate;
        var dtree = layui.dtree;
        //第一个实例
        tableIns = table.render({
            elem: '#userTable'
            , height: 312
            , url: '/user/loadAllUser' //数据接口
            , page: true //开启分页
            , toolbar: "#tableToolbar"
            , cols: [
                [ //表头
                    {width: 80, type: 'checkbox'}
                    , {field: 'id', title: 'ID', width: 80}
                    , {field: 'name', title: '用户姓名', width: 100}
                    , {field: 'loginname', title: '登录名称', width: 100}
                    , {field: 'deptname', title: '登录名称', width: 100}
                    , {field: 'leadername', title: '直接领导', width: 100}
                    , {field: 'hiredate', title: '入职时间', width: 100}
                    , {
                    field: 'sex', title: '性别', width: 100, templet: function (data) {
                        return data.sex == 1 ? '男' : '女';
                    }
                },
                    {
                        field: 'available', title: '是否可用', width: 100, templet: function (data) {
                            return data.available == 1 ? '可用' : '不可用';
                        }
                    }
                    , {field: 'remark', title: '备注', width: 100}
                    , {field: 'ordernum', title: '排序号', width: 100}
                    , {field: 'address', title: '用户地址', width: 100}
                    , {
                    field: 'imgpath', title: '头像', width: 130, templet: function (data) {
                        return "<img width='30' height='30' src='" + data.imgpath + "'>";
                    }
                }
                    , {title: '操作', width: 300, fixed: 'right', align: 'center', toolbar: '#cellToolbar'}
                ]
            ]
        });
        //弹出层的index
        var layerindex;

        //添加修改公用弹出层的路径
        var addFormUrl;


//监听事件
        table.on('toolbar(userTable)', function (obj) {
            // var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'add':
                    addUser();
                    break;
                // case 'batchDelete':
                //     layer.msg('批量删除');
                //     var checkStatus = table.checkStatus('userTable')
                //         , data = checkStatus.data;
                //
                //     layer.alert(JSON.stringify(data));
                //
                //     break;
            }
            ;
        });


        table.on('tool(userTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.data.id);

            switch (obj.event) {
                case 'update':
                    updateUser(obj);
                    break;
                case 'delete':
                    deleteUser(obj);
                    break;
                case 'resetUserPwd':
                    resetUserPwd(obj);
                    break;
                case 'dispatcherUserRole':
                    dispatcherUserRole(obj);
                    break;

            }
            ;
        });

        /**
         *
         * 添加
         */
        function addUser() {
            layer.msg('添加');
            layer.open({
                title: '添加用户',
                type: 1,
                area: ['700px', '500px'],
                content: $('#addForm'),
                resize: true,
                success: function (layero, index) {
                    //清空表单里面的数据
                    $("#addForm")[0].reset();
                    // 使下拉框为不弹出状态
                    // var mgr = $("#deptSelect");
                    // console.log(mgr);
                    // $("#mgr").val(mgr);
                    $(this).removeClass("layui-form-selected");
                    $("#test").removeClass("layui-show layui-anim layui-anim-upbit");
                    //清空pid内容
                    layerindex = index;
                    $.post("/user/loadUserMaxOrderNum", function (data) {
                        $("#ordernum").val(data.orderNum);
                    })

                    //绑定时间选择
                    laydate.render({
                        elem: "#hiredate",
                        type: 'date',
                        value: new Date()
                    })

                    addFormUrl = "/user/addUser";
                }
            });
        }
         /**
         *
         * 分配角色
         */
        function dispatcherUserRole(obj) {
             layer.open({
                 title: "为用户<" + obj.data.name + ">分配角色",
                 type: 1,
                 area: ['500px', '400px'],
                 content: $('#dispatcherRoleDiv'),
                 btn: ['分配角色', '取消分配'],
                 success: function(layero, index){
                     //初始化 角色表格
                     var tableIns = table.render({
                         elem: '#roleTable'
                         , height: 312
                         , url: '/role/queryRoleByUserid?id='+obj.data.id //数据接口
                         , cols: [
                             [ //表头
                                 {width: 80, type: 'checkbox'}
                                 , {field: 'id', title: 'ID'}
                                 , {field: 'name', title: '角色名称'}
                                 , {field: 'remark', title: '角色备注'}
                             ]
                         ]
                     });
                 },
                 yes: function (index, layero) {
                     var checkStatus = table.checkStatus('roleTable')
                         ,data = checkStatus.data;
                     var param = "id="+obj.data.id;
                     for (var i = 0; i < data.length; i++) {
                         var datum = data[i];
                            param+="&ids="+datum.id;
                     }
                     $.post("/user/dispatcherUserRole?"+param,function (data) {
                         layer.msg(data.msg);
                     })
                 }
                 ,btn2: function (index, layero) {
                     layer.close(index)
                 }

             })
        }

        /**
         * 修改用户
         * @param obj
         */
        function updateUser(obj) {
            layer.open({
                title: '修改用户',
                type: 1,
                area: ['700px', '500px'],
                content: $('#addForm'),
                success: function (layero, index) {
                    //清空表单里面的数据
                    $("#addForm")[0].reset();
                    //装载默认数据

                    form.val("addForm", obj.data);

                    form.val("addForm", {sex: obj.data.sex + ""});
                    form.val("addForm", {available: obj.data.available + ""});

                    $("#test").removeClass("layui-show layui-anim layui-anim-upbit");
                    // 下拉框回显
                    //设置下拉框里面的默认的上级用户的id
                    dtree.dataInit("userdepttree", obj.data.deptid);
                    //设置输入框里面的默认的上级用户名称
                    //获得当前选中的
                    var param = dtree.getNowParam("userdepttree");
                    $("#userdeptaccordiontreename").val(param.context);


                    //绑定时间选择
                    laydate.render({
                        elem: "#hiredate",
                        type: 'date',
                        value: new Date()
                    })

                    console.log(obj.data)
                    //根据领导的id查询领导信息(部门)并回显
                    $.post("/user/loadUserById", {id: obj.data.mgr}, function (data) {
                        var deptid = data.user.deptid;
                        dtree.dataInit("leaderdepttree", deptid);
                        var param = dtree.getNowParam("leaderdepttree");
                        $("#leaderdeptname").val(param.context);
                        renderSelect(deptid,function () {
                            
                        });
                        $("#deptSelect").val(data.user.id);
                        form.render('select');
                    })
                    layerindex = index;
                    addFormUrl = "/user/updateUser";
                }
            });
        }

        /**
         *删除用户
         *
         */

        function deleteUser(obj) {

            layer.confirm("确定要删除{" + obj.data.name + "}吗?", {icon: 3, title: '提示'}, function (index) {

                $.post("/user/deleteUser", {id: obj.data.id}, function (data) {
                    layer.msg(data.msg)
                    if (data.code == 200) {
                        //刷新 树 表格 下拉树
                        //刷新表格
                        $("#doReset").click();
                        //刷新左侧树
                        // window.parent.left.reloadTree();
                        //刷新下拉树
                        // loaduserdepttree();
                    }
                });
                layer.close(index);
            });


        }

        /**
         *重置密码
         *
         */

        function resetUserPwd(obj) {

            layer.confirm("确定要重置用户{" + obj.data.name + "}的密码吗?", {icon: 3, title: '提示'}, function (index) {

                $.post("/user/resetUserPwd", {id: obj.data.id}, function (data) {
                    layer.msg(data.msg)
                    if (data.code == 200) {
                        //刷新 树 表格 下拉树
                        //刷新表格
                        $("#doReset").click();
                        //刷新左侧树
                        // window.parent.left.reloadTree();
                        //刷新下拉树
                        // loaduserdepttree();
                    }
                });
                layer.close(index);
            });


        }


        //员工部门弹出层下拉树开始

        function loaduserdepttree() {
            var DTree = dtree.render({
                elem: "#userdepttree",
                method: "get",
                url: '/dept/loadAllAccordionDeptTree',
                icon: "1",
                dataStyle: "layuiStyle",  //使用layui风格的数据格式
                accordion: true
                , response: {
                    message: "msg",
                    statusCode: 0
                }
            });
        }

        loaduserdepttree();

        $("#userdeptaccordiontreename").on("click", function () {
            $(this).toggleClass("layui-form-selected");
            $("#test[name=divuser]").toggleClass("layui-show layui-anim layui-anim-upbit");
        });

        //下拉树选中
        dtree.on("node(userdepttree)", function (obj) {
            var param = dtree.getNowParam("userdepttree"); // 获取当前选中节点
            $("#deptid").val(param.nodeId);
            $("#userdeptaccordiontreename").val(obj.param.context);
            $("#userdeptaccordiontreename").toggleClass("layui-form-selected");
            $("#test[name=divuser]").toggleClass("layui-show layui-anim layui-anim-upbit");
        });

        //员工部门弹出层下拉树结束


        //直接领导部门弹出层下拉树开始

        function loadleaderdepttree() {
            var DTree = dtree.render({
                elem: "#leaderdepttree",
                method: "get",
                url: '/dept/loadAllAccordionDeptTree',
                icon: "1",
                dataStyle: "layuiStyle",  //使用layui风格的数据格式
                accordion: true
                , response: {
                    message: "msg",
                    statusCode: 0
                }
            });
        }

        loadleaderdepttree();

        $("#leaderdeptname").on("click", function () {
            $(this).toggleClass("layui-form-selected");
            $("#test[name=divleader]").toggleClass("layui-show layui-anim layui-anim-upbit");
        });

        function renderSelect(deptid,fn) {
            $.post("/user/loadUserByDeptId", {deptid: deptid}, function (objs) {
                var selectcontent = "<option value=''>请选</option>";
                for (var i = 0; i < objs.length; i++) {
                    var user = objs[i];

                    selectcontent += "<option value='" + user.id + "'>" + user.name + "</option>"
                }
                $("#deptSelect").html(selectcontent);
                form.render("select");
                if(fn!=undefined){
                    fn();
                }
            })
        }

//下拉树选中
        dtree.on("node(leaderdepttree)", function (obj) {
            var param = dtree.getNowParam("leaderdepttree"); // 获取当前选中节点
            $("#deptid").val(param.nodeId);
            $("#leaderdeptname").val(obj.param.context);
            $("#leaderdeptname").toggleClass("layui-form-selected");
            $("#test[name=divleader]").toggleClass("layui-show layui-anim layui-anim-upbit");
            renderSelect(param.nodeId);
        });

        //直接领导部门弹出层下拉树结束

        //当用户名称输入完 失去焦点时 为登录名生成 对应的拼音

        $("#name").blur(function () {
            var name = $("#name").val();
            var ordernum = $("#ordernum").val();

            //当修改时 不生成
            if (addFormUrl != "/user/updateUser") {
                $.post("/user/getUserPinYin", {name: name}, function (data) {
                    var pinyinname = data.loginname
                    pinyinname += ordernum;
                    $("#loginname").val(pinyinname);
                });
            }
        })

        //监控添加提交事件
        form.on("submit(release)", function (data) {
            var params = $("#addForm").serialize();
            console.log(params)
            var pid = $("#pid").val();
            $.post(addFormUrl, params, function (data) {
                layer.msg(data.msg);
            });

            //重置添加表单
            $("#addForm")[0].reset();
            //刷新表格 左侧树 弹出层表格
            // tableIns.reload();
            //刷新表格
            $("#doReset").click();
            //刷新左侧树
            window.parent.left.reloadTree();
            //刷新下拉树
            loaduserdepttree();

            $(this).removeClass("layui-form-selected");
            $("#test").removeClass("layui-show layui-anim layui-anim-upbit");
            layer.close(layerindex);
        });
        $("#cancel").click(function () {
            $("#addForm")[0].reset();
            $(this).removeClass("layui-form-selected");
            $("#test").removeClass("layui-show layui-anim layui-anim-upbit");
            layer.close(layerindex)
            //清空pid内容
            $("#pid").val("");
        })

        //监听查询事件
        form.on("submit(doSearch)", function (data) {
            var params = $("#searchFrm").serialize();
            tableIns.reload({
                url: '/user/loadAllUser?' + params
                // ,where:{
                //     page:1
                // }
            })
            //刷新表格
            return false;
        });

        //监控重置事件
        $("#doReset").click(function () {
            tableIns.reload({
                url: '/user/loadAllUser?'
                // ,where:{
                //     page:1
                // }
            })
            //重置搜索表单
            $("#searchFrm")[0].reset();
            //刷新表格
            return false;
        });

    });

    function reloadTable(userid) {
        tableIns.reload({
            url: '/user/loadAllUser?id=' + userid,
            // where:{
            //     page:1
            // }
        })
    }
</script>
</body>

</html>